package com.lbyl.util;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

/**
 * 用lrucache取代软引用
 * @author libin996@outlook.com
 */

public class MemoryCacheUtil {


    private LruCache<String, Bitmap> mMemoryCache;
//    private HashMap<String, SoftReference<Bitmap>> mMemoryCache;

    public MemoryCacheUtil(){
        long maxMemory = Runtime.getRuntime().maxMemory();//获取分配给app的最大内存
        mMemoryCache = new LruCache<String, Bitmap>((int)(maxMemory/8)){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }
        };
    }

    /**
     * 写内存缓存
     *
     * @param urlStr
     * @param bitmap
     */
    public void setMemoryCache(String urlStr, Bitmap bitmap) {
        mMemoryCache.put(urlStr, bitmap);
    }

    /**
     * 从内存中返回bitmap 或null
     *
     * @param urlStr
     * @return
     */
    public Bitmap getMemoryCache(String urlStr) {
        return mMemoryCache.get(urlStr);
    }
}
